<script setup lang='ts'>
import { ref } from 'vue';
import {
    add,
    counselors,
    delCounselor,
    editCounselor,
    getCounselor,
    getLabel,
    searchCounselor
} from '@/api/axios/counselorAxios';


const border = ref(true);
// 添加框
const dialogVisible = ref(false);

// 标签
const options = ref([]);
const labelOption = ref('');
getLabel().then(res => {
    // console.log(res.rows);
    labelOption.value = res.rows;
});

const data = ref({
    name: '',
    mobile: '',
    pageSize: 10,
    pageNum: 1
});

counselors().then(res => {
    console.log(res);
    options.value = res.rows;
});

const total = ref(0);
let tableData = ref(null);

function initCounselor() {
    searchCounselor(data.value).then(res => {
        // console.log(res);
        tableData.value = res.rows;
        total.value = res.total;

        tableData.value.map(item => {
            // console.log(item);
            if (item.mobile === '') {
                item.mobile = '暂无数据';
            }
            return item.mobile;
        });
    });
}

initCounselor();

// 分页
const onPageChange = (e) => {
    data.value.pageNum = e;
    initCounselor();
};

// 添加
function addCounselor() {
    formLabelAlign.value = {
        avatar: '',
        name: '',
        weight: 0,
        phone: '',
        location: '',
        infos: '',
        profession: '',
        labels: [],
        mobile: '',
        gender: '',
        userId: ''
    };
    dialogVisible.value = true;
    // console.log();
    disabled.value = false;

}


import type { FormProps } from 'element-plus';
// import { reactive } from 'vue'
const labelPosition = ref<FormProps['labelPosition']>('left');

const formLabelAlign = ref({
    avatar: '',
    name: '',
    weight: 0,
    phone: '',
    location: '',
    infos: '',
    profession: '',
    labels: [],
    mobile: '',
    gender: '',
    userId: '',
    id: '',
    status: ''
});

// 头像上传
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import type { UploadProps } from 'element-plus';

const imageUrl = ref('');

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // imageUrl.vasue = URL.createObjectURL(uploadFile.raw!);
    formLabelAlign.value.avatar = response.url;
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};

// 权重

const handleChange = (value: number) => {
    console.log(value);
};

let disabled = ref(false);


function save() {
    if (formLabelAlign.value.id) {
        // console.log(formLabelAlign.value);
        editCounselor(formLabelAlign.value).then(res => {
            // console.log(res);
            initCounselor();
            ElMessage({
                showClose: true,
                message: '修改成功',
                type: 'success'
            });
        });

    } else {
        console.log('add');

        for (const argumentsKey in options.value) {
            if (options.value[argumentsKey].nickName=== formLabelAlign.value.name){
                formLabelAlign.value.userId = options.value[argumentsKey].userId;
            }
        }
        add(formLabelAlign.value).then(res => {
            console.log(res);
            // tableData.value = res.rows
            initCounselor()
            ElMessage({
                showClose: true,
                message: '添加成功',
                type: 'success',
            })
        })

    }
    dialogVisible.value = false;
}

// 编辑
function edit(data) {
    dialogVisible.value = true;
    disabled.value = true;

    // formLabelAlign.value = data
    formLabelAlign.value = {
        id: data.id,
        userId: data.userId,
        location: data.location,
        status: data.status,
        avatar: data.avatar,
        gender: data.gender,
        infos: data.infos,
        mobile: data.mobile,
        phone: data.phone,
        name: data.name,
        profession: data.profession,
        weight: data.weight,
        labels: data.labels.map(item => item.label)
    };


}


// 搜索
function search() {
    initCounselor();
}

// 重置
function reset() {
    data.value = {
        name: '',
        mobile: '',
        pageSize: 10,
        pageNum: 1
    };
    initCounselor();
}

// 删除
import { ElMessageBox } from 'element-plus';
import { getToken } from '@/utils/auth';

const del = (data) => {
    ElMessageBox.confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            console.log(data);
            delCounselor(data.id).then(res => {
                console.log(res);
                initCounselor();
            });

            ElMessage({
                type: 'success',
                message: '删除成功'
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            });
        });
};
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const avatarUploadUrl = baseUrl + '/common/upload';
const header = {
    'Authorization': 'Bearer ' + getToken()
};
</script>

<template>
    <div>
        <ul class='gap-4 mb-4 items-center stuForm'>
            <li>
                <!--            姓名-->
                <span style='margin-right: 15px;font-size: 14px;'><b>姓名</b></span>
                <el-input
                    v-model='data.name'
                    style='width: 158px;'
                    size='large'
                    placeholder='请输入姓名'
                />
            </li>
            <li>
                <!--            电话-->
                <span style='margin-right: 15px;font-size: 14px;'><b>电话</b></span>
                <el-input
                    v-model='data.mobile'
                    style='width: 158px;'
                    size='large'
                    placeholder='请输入电话'
                />
            </li>
            <li style='margin-left: 50px;'>
                <el-button size='large' @click='reset'>重置</el-button>
                <el-button type='primary' size='large' @click='search'>搜索</el-button>
            </li>
        </ul>
        <div class='mb-4' style='margin-left: 35px'>
            <el-button type='primary' plain size='large' @click='addCounselor'>添加</el-button>
        </div>
        <div>
            <el-table :data='tableData' style='width: 95%;margin: 0 auto' :border=border>
                <el-table-column fixed type='index' label='序号' width='132' align='center' />
                <el-table-column prop='name' label='用户名称' align='center' width='131' />
                <el-table-column prop='mobile' label='联系电话' align='center' width='131' />
                <el-table-column prop='phone' label='办公电话' width='131' align='center' />
                <el-table-column prop='location' label='地址' align='center' />
                <el-table-column prop='createTime' label='创建时间' width='164' align='center' />
                <el-table-column fixed='right' label='操作' width='200' align='center'>
                    <template v-slot='scope'>
                        <el-button link type='primary' style='font-size: 13px' @click='edit(scope.row)'>编辑</el-button>
                        <el-button link type='primary' style='font-size: 13px' @click='del(scope.row)'>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class='pageNum'>
            <!--pageNum \ pageSize \ total -->
            <el-pagination background layout='prev, pager, next' :total='total'
                           v-model:page-size='data.pageSize' v-model:current-page='data.pageNum'
                           @currentChange='onPageChange'
            />
        </div>

        <!--    添加咨询师-->
        <el-dialog
            v-model='dialogVisible'
            title='添加'
            width='700'
        >
            <!--                添加表单-->
            <div style='padding: 0 10px'>
                <div style='margin: 20px' />
                <el-form
                    :label-position='labelPosition'
                    label-width='auto'
                    :model='formLabelAlign'
                    style='max-width: 630px'
                >

                    <el-form-item label='头像' style='font-weight: bold'>
                        <el-upload
                            class='avatar-uploader'
                            :action='avatarUploadUrl'
                            :show-file-list='false'
                            :on-success='handleAvatarSuccess'
                            :headers='header'
                            :before-upload='beforeAvatarUpload'
                        >
                            <img v-if='formLabelAlign.avatar' :src='baseUrl+formLabelAlign.avatar' class='avatar' />
                            <el-icon v-else class='avatar-uploader-icon'>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label='选择用户'>
                        <el-select
                            v-model='formLabelAlign.name'
                            placeholder='用户姓名'
                            style='width: 275px;'
                            :disabled='disabled'
                        >
                            <el-option
                                v-for='item in options'
                                :key='item.userId'
                                :label='item.nickName'
                                :value='item.nickName'
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label='权重'>
                        <el-input-number
                            v-model='formLabelAlign.weight'
                            class='mx-4'
                            :min='0'
                            :max='10'
                            controls-position='right'
                            @change='handleChange'
                            style='width: 270px;margin-left: -2px'
                        />
                    </el-form-item>

                    <el-form-item label='办公电话'>
                        <el-input v-model='formLabelAlign.phone' placeholder='请输入办公电话' />
                    </el-form-item>

                    <el-form-item label='标签设置'>

                        <el-select
                            v-model='formLabelAlign.labels'
                            multiple
                            placeholder='选择标签'
                            style='width: 562px'
                        >
                            <el-option
                                v-for='item in labelOption'
                                :key='item.label'
                                :label='item.label'
                                :value='item.label'
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label='专业擅长'>
                        <el-input
                            v-model='formLabelAlign.profession'
                            style='width: 562px;'
                            rows='4'
                            maxlength='300'
                            placeholder='请输入擅长内容'
                            show-word-limit
                            type='textarea'
                            resize='none'
                        />
                    </el-form-item>

                    <el-form-item label='老师简介'>
                        <el-input
                            v-model='formLabelAlign.infos'
                            style='width: 562px; '
                            rows='4'
                            maxlength='300'
                            placeholder='请输入简介信息'
                            show-word-limit
                            type='textarea'
                            resize='none'
                            class='textHeight'
                        />
                    </el-form-item>

                    <el-form-item label='办公地址'>
                        <el-input
                            v-model='formLabelAlign.location'
                            style='width: 562px;'
                            maxlength='50'
                            placeholder='请输入办公地址'
                            show-word-limit
                            type='textarea'
                            resize='none'
                        />
                    </el-form-item>

                    <div style='margin-left: 76%'>
                        <el-button @click='dialogVisible = false' size='large'>取消</el-button>
                        <el-button type='primary' @click='save' size='large'>
                            保存
                        </el-button>
                    </div>

                </el-form>
            </div>
        </el-dialog>
    </div>

    <!--    删除-->

</template>

<style lang='scss'>
.gap-4 {
    padding: 26px 25px 10px;
    width: 100%;
    margin-left: 20px;
}

.stuForm {
    display: flex;
    flex-wrap: wrap;

    li {
        margin-right: 20px;
    }
}

div.cell {
    height: 36px;
    font-size: 14px;
    line-height: 36px;
    padding: 9px 0 !important;
}

.pageNum {
    margin-top: 25px;
    float: right;
    margin-right: 50px;
}

.el-dialog__header {
    background-color: #1892ff;
    margin-right: 0;

    .el-dialog__title {
        font-size: 18px;
        color: #fff;
    }

    .el-dialog__headerbtn .el-dialog__close {
        color: #fff !important;
    }
}

.avatar-uploader .avatar {
    width: 148px;
    height: 148px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    text-align: center;
}

.el-textarea__inner .textHeight {
    height: 95px
}

</style>
